/**
 * TmPackSerialAction.java
 * Created at 2017-2-17
 * Created by xieshuang
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.basic.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.ImportExcelUtils;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.basic.model.TmPackSerial;
import com.broadtext.rms.basic.service.ITmPackSerialService;
import com.broadtext.rms.system.model.TmWoFile;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>ClassName: TmPackSerialAction</p>
 * <p>Description: 电池ID管理控制层</p>
 * <p>Author: xieshuang</p>
 * <p>Date: 2017-2-17</p>
 */
@Controller
@RequestMapping("/basic/packSerial")
public class TmPackSerialAction {
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(TmPackSerialAction.class);  
    /**
     * 注入service
     */
    @Autowired
    @Qualifier("tmPackSerialService")
    private ITmPackSerialService tmPackSerialService;
    
    //代码走查byte大小
    private static Integer BYTE_SIZE=2048;
    
    /**
     * <p>
     * Description: 查询区域信息
     * </p>
     * 
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/getPackSerial.mvc")
    @ResponseBody
    public void getPackSerial(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator<?> it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if(obj.get("value")!=null && !"".equals(obj.get("value")+"")){
                        map.put(obj.get("name")+"", obj.get("value"));
                    }
                }
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit()+1);
            EntityPageBean<TmPackSerial> pageBean = this.tmPackSerialService.findEntityPageByQuery(map, pageBounds);
            Map<String, Object> dataMap=new HashMap<String, Object>();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                logger.error("查询出错",e);
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * <p>
     * Description: 批量删除
     * </p>
     * 
     * 
     * @param request 请求
     * @param pkId id
     * @param response 返回对象
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/delete.mvc")
    @ResponseBody
    public void delete(HttpServletRequest request, String pkId, HttpServletResponse response) {
        //返回值
        Map dataMap;
        dataMap = new HashMap();
        //存储主键id
        String[] resIdArray;
        resIdArray = pkId.split(",");
        try {
            this.tmPackSerialService.delete(resIdArray,
                    String.valueOf(request.getSession().getAttribute("sys.userName")));
            dataMap.put("msg", "SUCCESS");
        } catch (DaoException e) {
            dataMap.put("msg", "FAILURE");
            logger.error("删除出错：",e);
        }
        RmsUtil.writeJsonStr(response, JSON.toJSONString(dataMap));
    }
    
    /**
     * 
     * <p>Description: 生成指定数量的电池ID</p>
     * @param request 请求
     * @param packQuantity 数量
     * @param response 响应
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/createPack.mvc")
    @ResponseBody
    public void createPack(HttpServletRequest request, @RequestParam("num")long packQuantity, HttpServletResponse response) throws DaoException{
        Map<String, String> dataMap;
        dataMap = new HashMap<String, String>();
        try {
            this.tmPackSerialService.createPack(packQuantity, String.valueOf(request.getSession().getAttribute("sys.userName")));
            dataMap.put("msg", "SUCCESS");
        } catch (Exception e) {
        	e.printStackTrace();
            dataMap.put("msg", "FAILURE");
            logger.error("创建电池ID出错：",e);
        }
        RmsUtil.writeJsonStr(response, JSON.toJSONString(dataMap));
    }
    
    /**
     * 
     * <p>Description: 生成指定数量的电池ID</p>
     * @param request 请求
     * @param packQuantity 数量
     * @param response 响应
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/customID.mvc")
    @ResponseBody
    public Map<String, Object> customID(HttpServletRequest request, @RequestParam("packCode")String packCode, HttpServletResponse response) throws DaoException{
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        try {
            TmPackSerial t = new TmPackSerial();
            t.setPkId(UUIDUtils.getUUID());
            t.setSerialNo(packCode);
            t.setDelFlag("0");
            t.setStatus("0");
            t.setCreateUser(String.valueOf(request.getSession().getAttribute("sys.userName")));
            t.setCreateDate(new Date());
            dataMap = this.tmPackSerialService.customID(t);
        } catch (Exception e) {
            e.printStackTrace();
            dataMap.put("msg", "FAILURE");
            logger.error("创建电池ID出错：",e);
        }
        return dataMap;
    }
    
    /**
     * 
     * <p>Description: 批量导入电池id</p>
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/batchImportPackCode.mvc")
    @ResponseBody
    public Map<String, Object> batchImportPackCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); 
        List<List<Object>> listob = null; 
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();
            //获取工单id
            while(iter.hasNext()){  
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){
                    //取得当前上传文件的文件名称  
                    String fileName = file.getOriginalFilename();  
                    InputStream in = file.getInputStream();
                    listob = ImportExcelUtils.getBankListByExcel(in, fileName);
                    for (int i = 0; i < listob.size(); i++) {
                        if(StringUtils.isNotBlank(listob.get(i).get(0).toString())){
                            TmPackSerial t = new TmPackSerial();
                            t.setPkId(UUIDUtils.getUUID());
                            t.setSerialNo(listob.get(i).get(0).toString());
                            t.setDelFlag("0");
                            t.setStatus("0");
                            t.setCreateUser(String.valueOf(request.getSession().getAttribute("sys.userName")));
                            t.setCreateDate(new Date());
                            this.tmPackSerialService.customID(t);
                        }
                    }
                } 
            }  
        } 
        dataMap.put("msg", "SUCCESS");
        return dataMap;
        
    }
    
    /**
     * 
     * <p>Description: 下载文件</p>
     * @param pkId
     * @param request
     * @param response
     */
    @RequestMapping(value = "/download.mvc")
    @ResponseBody
    public void download(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            //
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String("电池ID导入模板.xlsx".getBytes("gb2312"), "ISO8859-1"));
            response.setCharacterEncoding("iso-8859-1");
            //设置header jquery 捕获成功标志
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            
            InputStream inputStream = new FileInputStream(new File(request.getSession().getServletContext().getRealPath("/")+"电池ID导入模板.xlsx"));
            os = response.getOutputStream();
            byte[] b = new byte[BYTE_SIZE];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 
     * <p>Description: 获取各个状态的电池使用数量 包含使用 未使用 已使用三个状态</p>
     * @return map集合 
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/getPackUseStatus.mvc")
    @ResponseBody
    public Object getPackUseStatus() throws DaoException{
        return this.tmPackSerialService.getStatusCount();
    }
    /**
     * 
     * <p>Description: 验证数值是否过大</p>
     * @param packNum 生成id数量
     * @return map集合 
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/checkData.mvc")
    @ResponseBody
    public Object checkData(@RequestParam("packNum")long packNum) throws DaoException{
        return this.tmPackSerialService.checkData(packNum);
    }
    
    /**
     * 
     * <p>Description: 检查待删除电池状态是否包含已使用、报废</p>
     * @param pkId 主键id
     * @return 检查结果 true 可以删除， false 不可删除
     * @throws DaoException 异常
     */
    @RequestMapping(value="checkPackStatus.mvc")
    @ResponseBody
    public Object checkPackStatus(String pkId) throws DaoException{
        //存储主键id
        String[] ids;
        ids = pkId.split(",");
        return this.tmPackSerialService.checkPackStatus(ids);
    }
}
